import { z } from "zod";
import { codeartsrepoRequest, validateBranchName } from "../common/utils.js";
import { BranchSchema } from "../common/types.js";

// 创建分支
export const CreateNewBranchSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  branch: z.string().describe("新分支名称"),
  ref: z.string().describe("源分支名称"),
});

// 功能实现
export async function createNewBranch(
  projectId: string,
  repoId: string,
  branch: string,
  ref: string
) {
  // 验证分支名称
  const validBranchName = validateBranchName(branch);
  
  const response = await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/branches`, {
    method: "POST",
    body: {
      branch: validBranchName,
      ref
    }
  });
  
  return BranchSchema.parse(response);
}

// 获取所有分支
export async function getAllBranches(
  projectId: string,
  repoId: string
) {
  const response = await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/branches`);
  return z.array(BranchSchema).parse(response);
}

// 获取单个分支
export async function getBranch(
  projectId: string,
  repoId: string,
  branch: string
) {
  const response = await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/branches/${branch}`);
  return BranchSchema.parse(response);
}

// 删除分支
export async function deleteBranch(
  projectId: string,
  repoId: string,
  branch: string
) {
  await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/branches/${branch}`, {
    method: "DELETE"
  });
  
  return { success: true };
}

// 设置分支保护
export async function protectBranch(
  projectId: string,
  repoId: string,
  branch: string,
  protect: boolean = true
) {
  const method = protect ? "POST" : "DELETE";
  const url = `https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/branches/${branch}/protect`;
  
  const response = await codeartsrepoRequest(url, {
    method
  });
  
  return BranchSchema.parse(response);
} 